package cn.com.generaldata.os.ws.impl.web;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.pojo.Area;
import cn.com.generaldata.os.pojo.LArea;
import cn.com.generaldata.os.pojo.Role;
import cn.com.generaldata.os.pojo.Unit;
import cn.com.generaldata.os.service.common.AreaService;
import cn.com.generaldata.os.service.common.IndustryService;
import cn.com.generaldata.os.service.common.UserService;
import cn.com.generaldata.os.service.impl.web.UnitServiceForWeb;
import cn.com.generaldata.os.vo.ResultVO;
import cn.com.generaldata.os.vo.UnitVO;

@Component
@InjectName
public class UnitAction {

	private static Logger logger = LoggerFactory.getLogger(UnitAction.class);

	@Autowired
	private UnitServiceForWeb unitService;

	@Autowired
	private UserService userService;

	@Autowired
	private IndustryService industryService;

	@Autowired
	private AreaService areaService;

	// 导入企业
	public String importUnit(byte[] content, String fileName, String fileType) {
		// 导入的报表信息
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			logger.error("加载配置文件出错", ex);
		}

		String[] split = fileName.split(fileType);
		String saveFileName = split[0]; // 将用户上传的文件名进行按格式的修改，防止上传文件名重名而覆盖
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		saveFileName = String.valueOf(sdf.format(new Date())); // 登陆名后面加上传的日期
		// 日期后面加当前文件ID号、最大的序列号、文件的扩展名
		saveFileName += fileType; // 日期后面加最大的序列号、文件的扩展名

		if (content != null) {
			File file = new File(properties.getProperty("fileUploadPath").trim() + saveFileName); // 路径是存文件的路径
			try {
				FileOutputStream stream = new FileOutputStream(file);

				stream.write(content);
				stream.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error("上传文件出错", e);
			}
			String importIndicator = unitService.importUnits(file);
			// ReportExcelSectionVO sectionInfo = reportTmplate.getReportExcelSectionInfo(file, reportTypeId);
			// // sectionInfo.getReportFootEndRow();
			// reportService.import_report(user, reportProxyId, rType, timeType, yearType, timeDate, unitIndustryId,
			// reportVersion, quarterDate, file, sectionInfo, lasttimeReport);

			return importIndicator;
		}
		return null;
	}

	/**
	 * 添加单位
	 * unit 企业信息
	 */
	public String createUnit(UnitVO unit) {
		return unitService.createUnit(toPojo(unit));
	}

	/**
	 * 查找单位
	 * unitName 企业名称
	 * roleId 企业类型
	 */
	public ResultVO<UnitVO> queryUnits(String unitName, String roleId, String createYear, Integer pageNum) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("unitName");

		// if (StringUtils.isNotBlank(loginName)) {
		// filter.addRule(new FilterRule(FilterConstant.LIKE, "userLoginname", "%" + loginName.trim() + "%"));
		// }

		if (StringUtils.isNotBlank(unitName)) {
			filter.addRule(new FilterRule(FilterConstant.LIKE, "unitName", "%" + unitName.trim() + "%"));
		}

		if (StringUtils.isNotBlank(roleId)) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "role.id", roleId.trim()));
		}
		if (StringUtils.isNotBlank(createYear)) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "createYear", createYear.trim()));
		}
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return toVoResult(unitService.queryUnits(filter, page));
	}

	/**
	 * @function 删除单位
	 * @param ids
	 */
	public void removeUnits(List<String> ids) {
		if (ids != null) {
			String[] arrIds = new String[ids.size()];
			ids.toArray(arrIds);

			unitService.removeUnits(arrIds);
		}
	}

	/**
	 * @function 修改单位
	 * @param ids
	 */
	public UnitVO modifyUnit(UnitVO unit) {
		Unit modifyUnit = unitService.modifyUnit(toPojo(unit));
		// if (modifyUnit != null) {
		// Set<User> users = modifyUnit.getUsers();
		// for (User user : users) {
		// user.setRole(modifyUnit.getRole());
		// userService.modifyUser(user);
		// }
		// }
		return unitService.toVo(modifyUnit);
	}

	@At("/company/unit/view/?")
	@Ok("jsp:/static/company/unit/view")
	public UnitVO queryUnitById(String id) {
		return unitService.toVo(unitService.queryUnitById(id));
	}

	public ResultVO<UnitVO> queryUnitByIds(String ids, Integer pageNum) {

		if (StringUtils.isNotBlank(ids)) {
			Filter filter = new Filter();
			filter.setOrder(FilterConstant.ASC);
			filter.setSortBy("unitName");
			ResultVO<UnitVO> result = new ResultVO<UnitVO>();
			String[] split = ids.split(",");
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "id", split));
			Page page = null;
			if (pageNum != null) {
				page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
			}
			return toVoResult(unitService.queryUnits(filter, page));
		}
		return null;
	}

	@At("/unit/queryAllUsersByIndustryId")
	@Ok("json")
	public List<UnitVO> queryAllUsersByIndustryId(@Param("industryId") String industryId, @Param("areaId") String unitId) {
		String hql = "from Unit as u where (u.role.id='3' or u.role.id='5')";
		HashMap map = new HashMap();
		if (StringUtils.isNotBlank(unitId)) {
			hql += " and exists (select a.id from UnitRelation as a where a.cid=u.id and a.depth=1 and a.pid=:unitId)";
			map.put("unitId", unitId);
		}
		if (StringUtils.isNotBlank(industryId)) {
			hql += " and exists (select ui.id from UserIndustry as ui where exists(select us.id from User as us where us.id=ui.user.id and us.userUnit.id=u.id) and ui.industry.id=:industryId)";
			map.put("industryId", industryId);
		}
		return toVoResult(unitService.queryUnitsByhql(hql, map, null)).getOperationResult();

	}

	private Unit toPojo(UnitVO unit) {
		if (unit != null) {
			cn.com.generaldata.os.pojo.Unit userPO = unitService.queryUnitById(unit.getId());

			Role role = new Role();
			Area area = new Area();
			role.setId(unit.getRoleId());
			area.setId(unit.getAreaId());
			LArea lArea = null;
			if (StringUtils.isNotBlank(unit.getLareaId())) {
				lArea = new LArea();
				lArea.setId(unit.getLareaId());
			}

			if (userPO != null) {
				return new cn.com.generaldata.os.pojo.Unit(userPO.getId(), role, unit.getIndustryId(), area, lArea,
						unit.getUnitName(), unit.getUnitInstitutionName(), unit.getUnitInstitutionCode(),
						unit.getRegistAdd(), unit.getAddr(), userPO.getRegistArea(), userPO.getRegistLArea(),
						unit.getQh(), unit.getTel(), unit.getFax(), unit.getMobile(), unit.getZclx(), unit.getLsgx(),
						unit.getDl(), unit.getZl(), unit.getXl(), unit.getLm(), unit.getYyzt(), unit.getProduct1(),
						unit.getProduct2(), unit.getProduct3(), unit.getKgqk(), unit.getPractitioner(), unit.getQyjt(),
						unit.getSuperCompanyCode(), unit.getFr(), unit.getUnitProper(), userPO.getCreateYear(), null,
						unit.getProInfo(), unit.getKkx(), unit.getKky(), unit.getKkz(), unit.getDlx(), unit.getDly(),
						unit.getDlz(), unit.getPid(), userPO.getStatus());
			} else
				return new cn.com.generaldata.os.pojo.Unit(unit.getId(), role, unit.getIndustryId(), area, lArea,
						unit.getUnitName(), unit.getUnitInstitutionName(), unit.getUnitInstitutionCode(),
						unit.getRegistAdd(), unit.getAddr(), area, lArea, unit.getQh(), unit.getTel(), unit.getFax(),
						unit.getMobile(), unit.getZclx(), unit.getLsgx(), unit.getDl(), unit.getZl(), unit.getXl(),
						unit.getLm(), unit.getYyzt(), unit.getProduct1(), unit.getProduct2(), unit.getProduct3(),
						unit.getKgqk(), unit.getPractitioner(), unit.getQyjt(), unit.getSuperCompanyCode(),
						unit.getFr(), unit.getUnitProper(), unit.getCreateYear(), null, unit.getProInfo(),
						unit.getKkx(), unit.getKky(), unit.getKkz(), unit.getDlx(), unit.getDly(), unit.getDlz(),
						unit.getPid(), "1");
		}
		return null;
	}

	public UnitVO getUserUnit(String userId) {
		Unit userUnit = unitService.getUserUnit(userId);
		return unitService.toVo(userUnit);
	}

	@SuppressWarnings("unchecked")
	private ResultVO<UnitVO> toVoResult(cn.com.generaldata.os.paging.Result pResult) {
		ResultVO<UnitVO> result = new ResultVO<UnitVO>();

		List<UnitVO> units = new ArrayList<UnitVO>();
		for (Unit pUnit : (List<Unit>) pResult.getOperationResult()) {
			units.add(unitService.toVo(pUnit));
		}
		result.setOperationResult(units);
		result.setPageNumber(pResult.getPageNumber());
		result.setPageSize(pResult.getPageSize());
		result.setTotalCount(pResult.getTotalCount());

		return result;
	}

}
